import {getAnnouncementsApi,deleteAnnouncementApi,addAnnouncementApi} from "@/api/announcementManage";


const announcementManage = {
	namespaced: true,
	state: {
		paginationConfig: {
			current : 1,
			pageSize: 10,
			total: 0,
			pageSizeOptions: ['10', '30', '50', '100'],
			showQuickJumper: true,
			showSizeChanger: true,
			order: 'desc',
			orderBy: 'updatedAt',
			showTotal : (total)=>{
				let pageConfig = announcementManage.state.paginationConfig
				return `共  ${total}  条记录   第  ${pageConfig.current} / ${Math.ceil(pageConfig.total/pageConfig.pageSize)}  页 `
			},
		},
		order: 'desc',
		orderBy: 'createdAt',
	},
	mutations: {
		setTotal: (state, total) => {
			state.paginationConfig.total = total
		},
		setPage: (state, current) => {
			state.paginationConfig.current = current
		},
		setPageSize: (state, pageSize) => {
			state.paginationConfig.pageSize = pageSize
		},
		setOrder: (state, order) => {
			state.order = order
		},
		setOrderBy: (state, orderBy) => {
			state.orderBy = orderBy
		},
	},
	getters:{},
	actions: {
		getAnnouncements (context, params) {
			const pageSize = params && params.pageSize ? params.pageSize: context.state.paginationConfig.pageSize
			const page = params && params.page ? params.page : context.state.paginationConfig.current
			const order = params && params.order ? params.order : context.state.paginationConfig.order
			const orderBy = params && params.orderBy ? params.orderBy : context.state.paginationConfig.orderBy
			return new Promise((resolve, reject) => {
				getAnnouncementsApi({pageSize,page,order,orderBy})
					.then(res => {
						if (res.code === 0) {
							context.commit("setTotal", res.data.total)
							context.commit("setPage", res.data.current)
							context.commit("setPageSize", res.data.size)
							resolve(res.data.data)
						} else {
							reject(res)
						}
					}).catch(error => {
					console.error(error)
					reject(error)
				})
			})
		},
		addAnnouncement (context, params) {
			return new Promise((resolve, reject) => {
				addAnnouncementApi(params)
					.then(res => {
						if (res.code === 0) {
							resolve(res)
						} else {
							reject(res)
						}
					}).catch(error => {
					console.error(error)
					reject(error)
				})
			})
		},
		deleteAnnouncement (context, id) {
			return new Promise((resolve, reject) => {
				deleteAnnouncementApi(id)
					.then(res => {
						if (res.code === 0) {
							resolve(res)
						} else {
							reject(res)
						}
					}).catch(error => {
					console.error(error)
					reject(error)
				})
			})
		}
	},
}

export default announcementManage
